import time
from decimal import *
from django.views.generic.list import ListView
from django.views.generic.edit import DeleteView, UpdateView
from jrcsignal.models import JrcSignal
from jrcmodel.models import MyConstants, CST
from django.shortcuts import render_to_response
from django.contrib.auth.decorators import login_required
from django.http import HttpResponseRedirect
from django.template.context import RequestContext
from django.views.generic.dates import YearArchiveView, MonthArchiveView
from jrcsignal.viewmodel import SignalsOfYear

class ListSignalsView(ListView):
    model = JrcSignal
    template_name = "jrcsignal/jrcsignal_list.html"
    
    
class DeleteSignalView(DeleteView):
    model = JrcSignal
    template_name = "jrcsignal/jrcsignal_confirm_delete.html"
    
    # Add support for browsers which only accept GET and POST for now.
    def post(self, *args, **kwargs):
#        print "CST to return after delete is %d" % self.get_object().cst_id.pk
        self.success_url = "/jrcsignal/%d/" % self.get_object().cst_id.pk
        return self.delete(*args, **kwargs)


class UpdateSignalView(UpdateView):
    model = JrcSignal
    template_name = "jrcsignal/jrcsignal_form.html"
    def get_success_url(self):
        print "First date: %s" % self.object.date_first
        return "/jrcsignal/"

class SignalsMonthArchiveView(MonthArchiveView):
    model = JrcSignal
    date_field = "date_first"
    paginate_by = 300
    allow_empty = True


@login_required
def signals_by_month(request, cst_id):
    if cst_id == 0:
        return HttpResponseRedirect("/jrcsignal/csts/")

    cst = CST.objects.get(pk = cst_id)

    signals_by_years = [
        SignalsOfYear(cst_id, 2008)
        , SignalsOfYear(cst_id, 2009)
        , SignalsOfYear(cst_id, 2010)
        , SignalsOfYear(cst_id, 2011)
        , SignalsOfYear(cst_id, 2012)
    ]
    
#    print signals_by_years[0]
    
    return render_to_response(
                "jrcsignal/signals_by_month.html"
                , {
                   "by_years": signals_by_years
                   , "cst": cst
                }
                , context_instance = RequestContext(request))

@login_required
def parse_signals(request, cst_id, clean = ""):
    """
    Displays form to input signals and parses signals for specific CST, which are POSTed as multilines text.
    """
    cst = CST.objects.get(pk = cst_id)
    total_signals = 0

    # Determine whether we need to truncate signals for current CST before import
    need_truncating = False
    if clean == "clean":
        total_signals = JrcSignal.objects.filter(cst_id = cst.pk).count()
        need_truncating = True

    # Import is done on POST
    if request.method == "POST":
        
        if need_truncating:
            # Check if user understood CST signals truncating
            if request.POST.get("delete_signals") != "1":
                return HttpResponseRedirect("/jrcsignal/%d/parse/clean/" % int(cst_id))
            # Delete signals for CST
            JrcSignal.objects.filter(cst_id = cst_id).delete()

        nr = 1
        # Loop all lines
        lines = request.POST.get("signals").split("\n")
        is_first = True
        for l in lines:
            ar = l.split(",")
            # We are interested only in proper formatted lines
            if len(ar) == 10:
                # Did we search for CST?
                if cst == None:
                    try:
                        cst = CST.objects.get(name = ar[1].strip())
                    except:
                        return HttpResponseRedirect("/jrcsignal/badcst/%s" % ar[1].strip())

                # Each signal is separated by 2 lines, join them
                if is_first:
                    s = JrcSignal()
                    s.status_id = MyConstants.STATUS_APPROVED
                    s.cst_id = cst

                    parse_signal(s, ar, is_first)
                    is_first = False
                else:
                    parse_signal(s, ar, is_first)
#                    print s
                    s.save()
                    is_first = True
            else:
                print "Line %d has less than 10 elements!" % nr
            nr += 1

        return HttpResponseRedirect("/jrcsignal/%d/" % cst.pk)
    return render_to_response(
                "jrcsignal/parsesignals.html"
                , {
                   "cst": cst
                   , "need_truncating": need_truncating
                   , "total_signals": total_signals
                }
                , context_instance = RequestContext(request))

def parse_signal(s, ar, is_first):
    """
    Parses array (pays attention if this is first or second part of signal)
    """
    direction = ar[2][0]
    print "Direction: %s" % direction
#        dt = time.strptime("%s-%s-%s" % (ar[3], ar[4], ar[5]), "%Y-%m-%d")
    dt = "%s-%s-%s" % (ar[3], ar[4], ar[5])
    print dt
#        entry_value = Decimal("%s.%s" % (ar[6], ar[7]))
#        print entry_value
    v = Decimal("%s.%s" % (ar[7], ar[8]))
    print v

    if is_first:
        s.date_first = dt
        s.direction_first = direction
        s.entry_value = v
    else:
        s.date_second = dt
        s.direction_second = direction
        s.exit_value = v

